package com.zx._01_基础._019_servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 初始化页面
 *
 * @author 张雪
 */
public class CookieServlet2 extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 1.获得客户端的cookies
        Cookie[] cookies = request.getCookies();
        // 2.如果没有任何cookies，则直接跳转到登录页面
        if (cookies == null) {
            response.sendRedirect("index.jsp");
            return;
        } else {// 有的话，就去遍历所有cookies寻找自己需要的
            for (Cookie cookie : cookies) {
                // 如果找到需要的cookies，则提取其中自己需要的内容
                if (cookie.getName().equals("login_information")) {
                    String[] information = cookie.getValue().split("0.0");
                    String name = information[0];
                    String password = information[1];
                    request.setAttribute("name", name);
                    request.setAttribute("password", password);
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                    return;
                } else {
                    response.sendRedirect("index.jsp");
                    return;
                }
            }
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
